//
//  TwoViewController.m
//  fp
//
//  Created by xingshuai on 2020/10/9.
//

#import "TwoViewController.h"

#import "RoomCollectionViewCell.h"
#import "XSUserRoomModel.h"

static NSString *identifier = @"XARoomCollectionCellID";
static NSString *headerIdentifier = @"XAHeadCollectionCellID";


@interface TwoViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

// 数据展示
@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) NSArray *list;
@property (nonatomic, strong) NSMutableArray *modelList;
@property (nonatomic, strong) NSMutableArray *selectList;
@property (nonatomic, strong) UIButton *editBtn;
@property (nonatomic, strong) UIButton *allBtn;
@property (nonatomic, strong) UIButton *delBtn;
@property (nonatomic, assign) NSInteger selectNum;

@end

@implementation TwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.list = @[@"今天",@"更早"];
    
    self.currentnavType = XSCurrentNavViewTypeUser;
    // 添加试图内容
    [self creatClassRoomViewUI];
    
    [self requestData];
    
}
// 记录是否历史记录，是则显示学习进度条，否则不显示
-(void)setIsHisTory:(BOOL)isHisTory {
    _isHisTory = isHisTory;
}

-(NSMutableArray *)modelList {
    if (!_modelList) {
        _modelList = [[NSMutableArray alloc]init];
    }
    return _modelList;
}

-(NSMutableArray *)selectList {
    if (!_selectList) {
        _selectList = [[NSMutableArray alloc]init];
    }
    return _selectList;
}

// 模拟获取数据
-(void)requestData {
    
    [self.modelList removeAllObjects];
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    NSMutableArray *arr1 = [[NSMutableArray alloc]init];
    
    NSInteger tol = 0;
    tol = self.isHisTory ? 5 : 4;
    
    for (int i = 0; i < tol; i ++) {
        XSUserRoomModel *model = [[XSUserRoomModel alloc]init];
        [arr addObject:model];
    }
    [self.modelList addObject:arr];
        
    for (int i = 0; i < tol + 2; i ++) {
        XSUserRoomModel *model = [[XSUserRoomModel alloc]init];
        [arr1 addObject:model];
    }
    [self.modelList addObject:arr1];
    
    [self.collection reloadData];
}

// 初始化ui
-(void)creatClassRoomViewUI {
    
    [self.navView addSubview:self.editBtn];
    [self.editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navLabel);
        make.right.equalTo(self.navView.mas_right).offset(-15);
        make.size.mas_offset(CGSizeMake(55, 30));
    }];
    
    [self.navView addSubview:self.allBtn];
    [self.allBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navLabel);
        make.right.equalTo(self.editBtn.mas_left);
        make.height.mas_offset(30);
    }];
    
    [self.navView addSubview:self.delBtn];
    [self.delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navLabel);
        make.right.equalTo(self.allBtn.mas_left).offset(-15);
        make.height.mas_offset(30);
    }];
    
    [self.view addSubview:self.collection];
    [self.collection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.top.equalTo(self.navView.mas_bottom);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.bottom.equalTo(self.view).offset(-5);
    }];
}

// 初始化collection
- (UICollectionView *)collection {
    if (!_collection) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = 41;
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowLayout.headerReferenceSize = CGSizeMake(ScreenWidth*0.7, 78);
        
        _collection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        [_collection registerClass:[RoomCollectionViewCell class] forCellWithReuseIdentifier:identifier];
        _collection.showsHorizontalScrollIndicator = NO;
        _collection.dataSource = self;
        _collection.delegate = self;
        _collection.backgroundColor = [UIColor whiteColor];
        _collection.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
        
        //注册一种cell--->注册头部视图
        [_collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
    }
    return _collection;
}

#pragma mark - UICollectionViewDelegateFlowLayout
// 返回cell的尺寸大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((self.collection.frame.size.width-50)/3, (self.collection.frame.size.width-50)/3/1.15);
}

#pragma mark - deleDate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.modelList.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [[self.modelList objectAtIndex:section] count];
}
// 分区头部
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *headView;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
        
        UILabel * label = [headView viewWithTag:101];
        if(!label){
            label = [[UILabel alloc]initWithFrame:CGRectMake(10, 28, 100, 50)];
            label.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:20];
            label.tag = 101;
            [headView addSubview:label];
        }
        label.text = [self.list objectAtIndex:indexPath.section];
    }
    return headView;
}

// cell内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    RoomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.model = [[self.modelList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    // 是否历史记录（只有历史记录显示学习进度）
    cell.isHidenPro = self.isHisTory ? NO : YES;
    
    return cell;
}

// cell点击相应
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // 编辑状态点击选中/取消选中，否则点击播放
    if (self.editBtn.selected) {
        NSMutableArray *rows = [self.modelList objectAtIndex:indexPath.section];
        XSUserRoomModel *selectModel = [rows objectAtIndex:indexPath.row];
        selectModel.isSelect = !selectModel.isSelect;
        // 记录选中的数据个数刷新删除按钮文字
        if (selectModel.isSelect) {
            self.selectNum += 1;
        } else {
            self.selectNum -= 1;
        }
                
        [self.delBtn setTitle:[NSString stringWithFormat:@"删除(%ld)",self.selectNum] forState:UIControlStateNormal];
        
        // 这里判断数据在编辑状态下是否有数据未选中，以此切换全选按钮选中状态
        __block BOOL isAllSelect = YES;
        [self.modelList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSMutableArray *secArr = obj;
            [secArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                XSUserRoomModel *model = obj;
                if (!model.isSelect) {
                    isAllSelect = NO;
                    *stop = YES;
                }
            }];
        }];
        // 改变全选按钮状态
        if (isAllSelect == YES) {
            self.allBtn.selected = YES;
        }else{
            self.allBtn.selected = NO;
        }
        
        [self.collection reloadData];
    } else {
        // 还没有播放器，别费劲了
    }
}

// 编辑按钮
- (UIButton *)editBtn {
    if (!_editBtn) {
        _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_editBtn setTitleColor:[UIColor colorWithHexString:@"#606060"] forState:UIControlStateNormal];
        _editBtn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
        [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [_editBtn setTitle:@"取消" forState:UIControlStateSelected];
        [_editBtn addTarget:self action:@selector(clickEditBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editBtn;
}

// 全选按钮
- (UIButton *)allBtn {
    if (!_allBtn) {
        _allBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _allBtn.hidden = YES;
        [_allBtn setTitleColor:[UIColor colorWithHexString:@"#606060"] forState:UIControlStateNormal];
        _allBtn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
        [_allBtn setTitle:@"全选" forState:UIControlStateNormal];
        [_allBtn setTitle:@"取消全选" forState:UIControlStateSelected];
        [_allBtn addTarget:self action:@selector(clickAllBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _allBtn;
}

// 删除按钮
- (UIButton *)delBtn {
    if (!_delBtn) {
        _delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _delBtn.hidden = YES;
        [_delBtn setTitleColor:[UIColor colorWithHexString:@"#4E75FF"] forState:UIControlStateNormal];
        _delBtn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
        [_delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
        [_delBtn addTarget:self action:@selector(clickDelBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _delBtn;
}

// 编辑按钮响应
-(void)clickEditBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    // 编辑状态显示全选和删除按钮
    self.allBtn.hidden = !sender.selected;
    self.delBtn.hidden = !sender.selected;
    
    // 根据编辑按钮选中状态判断决定是否进入编辑状态
    for (NSArray *arr in self.modelList) {
        for (XSUserRoomModel *model in arr) {
            model.isEdit = sender.selected;
        }
    }
    
    // 取消编辑时清空编辑状态选中的数据
    if (!sender.selected) {
        for (NSArray *arr in self.modelList) {
            for (XSUserRoomModel *model in arr) {
                model.isSelect = sender.selected;
            }
        }
        self.selectNum = 0;
        self.allBtn.selected = NO;
        [self.delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    }
    
    [self.collection reloadData];
}

// 全选按钮响应
-(void)clickAllBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.selectNum = 0;
    // 全选状态根据选中数据刷新删除按钮显示文字
    if (sender.selected) {
        for (NSArray *arr in self.modelList) {
            for (XSUserRoomModel *model in arr) {
                model.isSelect = sender.selected;
            }
            self.selectNum += arr.count;
        }
    } else {   // 取消全选清空记录的选中状态
        for (NSArray *arr in self.modelList) {
            for (XSUserRoomModel *model in arr) {
                model.isSelect = sender.selected;
            }
        }
        self.selectNum = 0;
    }
    
    [self.delBtn setTitle:[NSString stringWithFormat:@"删除(%ld)",self.selectNum] forState:UIControlStateNormal];
    [self.collection reloadData];
}

// 删除按钮响应
-(void)clickDelBtn {
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
